//
//  CurrentIncidentDetailViewController.m
//  Runone
//
//  Created by runone02 on 16/12/7.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "CurrentIncidentDetailViewController.h"
#import "CurrentInidentHeaderView.h"
#import "IncidentDetailCell.h"
#import "ROPointAnnotation.h"
#import "CustomAnnotationView.h"
#import "CustomCallOutView.h"
#import "RequestGinsengModel.h"
#import "RequestHelper.h"
#import "AppLocalManager.h"
#import "AppDelegate.h"
#import "MJRefresh.h"
#import "EventDetailModel.h"
#import "MJExtension.h"
#import "EventBaseInfoModel.h"
#import "EventDealListModel.h"
#import "SecetionHeaderView.h"
#import "CameraGunDetailViewController.h"
#import "RightCodeTool.h"
#import "EventPictureCell.h"
#import "EventCellFrame.h"
#import "SGImagePickerController.h"
#import "UIView+Addition.h"
#import "OneConst.h"
#import "CameraDetailController.h"
#import "OneConst.h"
#import "ROActionSheet.h"
#import "LittleVideoViewController.h"
#import "AppConstants.h"
#import "EnlargeMapViewController.h"
#import "CameraDetailController.h"
#import "SDImageCache.h"
#import "SVProgressHUD.h"
#import "BCNetAPIClient.h"
#import "RightCodeTool.h"
#import "AJPhotoPickerViewController.h"
#import "AJPhotoBrowserViewController.h"
#import "ROImagePickViewController.h"

@interface CurrentIncidentDetailViewController ()<UITableViewDelegate, UITableViewDataSource,AJPhotoPickerProtocol,AJPhotoBrowserDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) CurrentInidentHeaderView *headerView;//头部

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong)  EventDetailModel *deatilModel;

@property (nonatomic, strong) NSMutableArray *annotationsArray;

@property (nonatomic, strong) DeviceBaseInfo *minDistanceCamera;//最近的摄像枪model

@property (assign, nonatomic) AllIconType type;

@property (nonatomic, strong) ROActionSheet *sheet;

@property (nonatomic, strong) HighwayMergeRoadRecordModel *currentRoadModel; //当前事件的

@property (nonatomic, strong) NSMutableArray *loadImageArr;

@property (strong, nonatomic) NSMutableArray *photos;

@property (strong, nonatomic) NSMutableArray *originalImgArr;

@end

@implementation CurrentIncidentDetailViewController

#pragma   --------事故事件详情

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _originalImgArr   = [[NSMutableArray alloc] init];
    _photos           = [[NSMutableArray alloc] init];
    _type             = AllIconTypeIncident;
    _currentRoadModel = [[HighwayMergeRoadRecordModel alloc] init];
    _annotationsArray = [[NSMutableArray alloc] init];
    _deatilModel      = [[EventDetailModel alloc] init];
    _dataArray        = [[NSMutableArray alloc] init];
    
    [self loadIncidentData];
    [self configTableView];
    [self configNavigationbar]; // 导航栏
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden            = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [_sheet hiddenSheet];
}

- (void) configNavigationbar {
    if ([[RightCodeTool sharedTool] rightIsEqualTO:@"P04010103"]) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigation_camera"] style:UIBarButtonItemStylePlain target:self action:@selector(addPictureOrVideo)];
    }
    self.view.backgroundColor=[UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.size     = CGSizeMake(100, 30);
    titleLabel.text     = @"事故事件详情";
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
}

- (void) addPictureOrVideo {
    [self UpLoadPictures];
}

- (void)UpLoadPictures {
    [[SDImageCache sharedImageCache] clearMemory];
    AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
    picker.maximumNumberOfSelection = 5;
    picker.multipleSelection        = YES;
    picker.assetsFilter             = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups          = YES;
    picker.delegate                 = self;
    picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    [self presentViewController:picker animated:YES completion:nil];
}

//选择图片
-(void)requestTestUpdateImage:(RequestGinsengModel *)RequestGinseng Image:(NSArray  *)arr {
    [SVProgressHUD showWithStatus:@"正在上传图片,请稍后......"];
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic=
    @{@"methodName":RequestGinseng.MethodName,@"updatedtime":RequestGinseng.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":RequestGinseng.DataValue};
    
    [BCNetAPIClient PostVideosAndImages:GetEventDataURL parameters:dic imageArray:arr videoArray:nil success:^(id responseObjecet) {
        [SVProgressHUD showSuccessWithStatus:@"上报成功"];
        [self loadIncidentData];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD showSuccessWithStatus:@"上报失败"];
    }];
}

-(NSString *)IncidentUIDAndDealDetail:(NSString *)IncidentUID {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"EventUID\",\"value\":\"%@\"}]",IncidentUID];
    return valueStr;
}
- (void)loadIncidentData { //事故事件
    [SVProgressHUD showWithStatus:@"正在加载..."];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *GetAccidentEventDetailInfoModel=[[RequestGinsengModel alloc] init];
    GetAccidentEventDetailInfoModel.URL         = GetEventDataURL;
    GetAccidentEventDetailInfoModel.DataValue   = [self DataValueStr:self.CEModel.IncidentUID];
    GetAccidentEventDetailInfoModel.UpdatedTime = @"";
    GetAccidentEventDetailInfoModel.SystemCode  = @"GuangleHighway";
    GetAccidentEventDetailInfoModel.MethodName  = @"GetAccidentEventDetailInfo";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        [_dataArray removeAllObjects];
        [SVProgressHUD showSuccessWithStatus:@"加载成功"];
        if ([[RightCodeTool sharedTool] rightIsEqualTO:@"P04010101"]) {
            _deatilModel = [EventDetailModel mj_objectWithKeyValues:requestOutginseng.DataValue];
            for (EventDealListModel *dealModel in _deatilModel.EventDealList) {
                EventCellFrame *cellF = [[EventCellFrame alloc] init];
                cellF.lModel = dealModel;
                
                [_dataArray addObject:cellF];
            }
            [self configHeaderView];
            _headerView.eventModel = _deatilModel;
            [self.tableView reloadData];
        }
            };
    [requestHelper RequestGinsengModel:GetAccidentEventDetailInfoModel andPushController:self];
}

- (void) configTableView {
    self.tableView.contentInset   = UIEdgeInsetsMake(64, 0, 0, 0);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.bounces        = NO;
    self.tableView.delegate       = self;
    self.tableView.dataSource     = self;
    
}

- (void) configHeaderView {
    _headerView            = [[[NSBundle mainBundle] loadNibNamed:@"CurrentInidentHeaderView" owner:self options:nil] lastObject];
    _headerView.frame      = CGRectMake(0, 0, self.view.bounds.size.width,356);
    _headerView.ceModel    = _CEModel;
    _headerView.eventModel = _deatilModel;
    [_headerView.enlargeBtn addTarget:self action:@selector(enlargeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_headerView.cameraGunBtn addTarget:self action:@selector(cameraGunClick) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = _headerView;
}

//放大地图
- (void) enlargeBtnClick {
    [[SDImageCache sharedImageCache] clearMemory];
    EnlargeMapViewController *vc = [[EnlargeMapViewController alloc] init];
    vc.la                        = [_CEModel.Latitude floatValue];
    vc.lo                        = [_CEModel.Longitude floatValue];
    vc.type                      = _type;
    [self presentViewController:vc animated:YES completion:nil];
}

//摄像枪点击
- (void) cameraGunClick {
    [[SDImageCache sharedImageCache] clearMemory];
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    for (HighwayMergeRoadRecordModel *model in myDelegate.HighWayRoadArray) {
        if ([model.RoadUID isEqualToString:_CEModel.RoadUID]) {
            _currentRoadModel = model;
        }
    }
    
    CameraDetailController *vc = [[CameraDetailController alloc]init];
    vc.deviceBaseInfo          = _headerView.deviceMoel;
    vc.roadType                = [_headerView.ceModel.RoadDerection integerValue];
    vc.currentRoadModel        = _currentRoadModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - tableviewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EventPictureCell *cell = [EventPictureCell cellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    EventCellFrame *cellF = _dataArray[indexPath.row];
    cell.cellFrame = cellF;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    EventCellFrame *cellF =  _dataArray[indexPath.row] ;
    return cellF.cellH;
}

- (NSString *)DataValueStr:(NSString *)IncidentUID {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"EventUID\",\"value\":\"%@\"}]",IncidentUID];
    return valueStr;
}
#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    [self.photos removeAllObjects];
    [self.originalImgArr removeAllObjects];
    [self.photos addObjectsFromArray:assets];
    for (int i = 0 ; i < self.photos.count; i++) {
        ALAsset *asset = self.photos[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [_originalImgArr addObject:tempImg];
    }
    RequestGinsengModel *GetConstructionInfoModel=[[RequestGinsengModel alloc] init];
    GetConstructionInfoModel.URL         = GetEventDataURL;
    GetConstructionInfoModel.DataValue   = [self IncidentUIDAndDealDetail:self.CEModel.IncidentUID];
    GetConstructionInfoModel.UpdatedTime = @"";
    GetConstructionInfoModel.SystemCode  = @"GuangleHighway";
    GetConstructionInfoModel.MethodName  = @"ReportAccidentEventDetailInfo";
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self requestTestUpdateImage:GetConstructionInfoModel Image:_originalImgArr];
    
}

- (void)photoBrowser:(AJPhotoBrowserViewController *)vc didDonePhotos:(NSArray *)photos {
    [vc dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    [self checkCameraAvailability:^(BOOL auth) {
        if (!auth) {
            NSLog(@"没有访问相机权限");
            return;
        }
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing   = NO;
        cameraUI.delegate        = self;
        cameraUI.sourceType      = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        [self presentViewController: cameraUI animated: YES completion:nil];
    }];
}

- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        NSLog(@"保存到相册成功");
        AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
        picker.maximumNumberOfSelection = 5;
        picker.multipleSelection        = YES;
        picker.assetsFilter             = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups          = YES;
        picker.delegate                 = self;
        picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return YES;
        }];
        [self dismissViewControllerAnimated:NO completion:nil];
        [self presentViewController:picker animated:NO completion:nil];
    }else{
        NSLog(@"保存到相册出错%@", error);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
//     [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDisk];
    
    [[SDImageCache sharedImageCache] clearMemory];
}
@end
